package com.station.search.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Charsets;
import com.google.common.hash.Hashing;
import com.station.search.common.domain.WebResponse;
import com.station.search.common.domain.WebResponseBuilder;
import com.station.search.constant.DeleteEnum;
import com.station.search.constant.UserDeactivageEnum;
import com.station.search.domain.StationUser;
import com.station.search.domain.converter.StationUserConverter;
import com.station.search.domain.vo.StationUserVO;
import com.station.search.service.StationUserService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author: JT
 * @date: 2021/9/8
 * @Title: 台站用户 Web控制器
 */
@RestController
@RequestMapping("/stations/users")
public class StationUserController {

    @Resource
    private StationUserService stationUserService;

    @PostMapping
    public WebResponse addStationUser(@RequestBody StationUserVO stationUserVO) {
        StationUser stationUser = StationUserConverter.INSTANCE.voToDo(stationUserVO);

        if (StringUtils.isEmpty(stationUser.getIsDeactivage())) {
            stationUser.setIsDeactivage(UserDeactivageEnum.NOT_DEACTIVAGE.getValue());
        }

        int salt = stationUser.getUsername().hashCode();
        // 密码加密方式  md5(原密码+用户名Hash)
        stationUser.setPassword(
                Hashing.md5().newHasher().putString(
                        String.format("%s%s", stationUser.getPassword(), salt), Charsets.UTF_8
                ).hash().toString()
        );
        stationUserService.save(stationUser);
        return WebResponseBuilder.ok("用户[{}]添加成功！", stationUser.getUsername());
    }


    @DeleteMapping("/{userId}")
    public WebResponse deleteUser(@PathVariable("userId") Integer userId) {
        StationUser stationUser = stationUserService.getById(userId);
        stationUser.setIsDeleted(DeleteEnum.IS_DELETED.getValue());
        stationUser.setDeletedDate(new Date());
        stationUserService.updateById(stationUser);
        return WebResponseBuilder.ok("台站用户[{}]已删除成功！", stationUser.getUsername());
    }

    @GetMapping
    public WebResponse<List<StationUser>> queryUsers(@RequestParam("page") Long page, @RequestParam("pageSize") Long pageSize) {
        Page<StationUser> stationUserPage = new Page<StationUser>(page, pageSize);
        IPage<StationUser> stationUserIPage = stationUserService.listAsPage(stationUserPage);
        return WebResponseBuilder.ok("获取用户列表成功！")
                .data(stationUserIPage);
    }
}
